package org.abettor.nookinfo.joke;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.abettor.nookinfo.AddressConstant;
import org.abettor.nookinfo.R;
import org.abettor.nookinfo.ads.YoumiManager;
import org.abettor.nookinfo.modal.Pair;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;

/**
 * 笑话分类页面
 * @author shawn
 *
 */
public class JokeCategory extends Activity
{
	private static final int REFRESHED = 1;//菜单更新已完成事件
	private static final int FAILED = 2;//菜单更新失败时间
	private YoumiManager youmi = new YoumiManager(this);
	private List<Pair<String, Integer>> categoryList = new ArrayList<Pair<String, Integer>>();
	private ProgressDialog progressDialog = null;//进度条对话框
	private Worker worker = null;//网络访问线程
	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			if(msg.what == REFRESHED)
			{
				//	将从网上更新来的菜单信息绘制到界面上
				LinearLayout layout = (LinearLayout) findViewById(R.id.jokeCategoryLayout);
				layout.removeAllViews();
				for(Pair<String, Integer> pair : categoryList)
				{
					final Pair<String, Integer> thePair = pair;
					Button btn = new Button(JokeCategory.this);
					btn.setText(thePair.first);
					btn.setTextColor(Color.WHITE);
					btn.setBackgroundResource(R.drawable.joke_button);
					//	设置按钮事件
					btn.setOnClickListener(new OnClickListener()
					{
						@Override
						public void onClick(View view)
						{
							//	打开相应类型所对应的文章内容列表
							Bundle extras = new Bundle();
							extras.putInt(JokeList.JOKE_CATEGORY_ID, thePair.second);
							extras.putString(JokeList.JOKE_CATEGORY_NAME, thePair.first);
							Intent jokeListIntent = new Intent();
							jokeListIntent.setClass(JokeCategory.this, JokeList.class);
							jokeListIntent.putExtras(extras);
							JokeCategory.this.startActivity(jokeListIntent);
						}
					});
					layout.addView(btn);
				}
				ScrollView scroll = (ScrollView) findViewById(R.id.jokeCategoryScroll);
				scroll.scrollTo(0, 0);

				//	按照一定的概率显示广告
				Random rand = new Random(System.currentTimeMillis());
				int val = rand.nextInt(99);
				if(val < 20)
				{
					youmi.showYoumi(YoumiManager.Position.middle, Color.WHITE, Color.BLACK, 0xAA);
				}
			}
			else if(msg.what == FAILED)
			{
				Builder builder = new Builder(JokeCategory.this);
				builder.setTitle(R.string.joke_category_fail_title);
				builder.setMessage(R.string.joke_category_fail_content);
				builder.setPositiveButton(R.string.joke_category_fail_btn_ok, new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialoginterface, int i)
					{
						dialoginterface.dismiss();
					}
				});
				builder.show();
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.joke_category);
		if(categoryList.isEmpty())
		{
			//	如果菜单没有更新过，就进行更新
			onUpdateClicked(null);
		}
		else
		{
			Message msg = new Message();
			msg.what = REFRESHED;
			handler.sendMessage(msg);
		}
	}

	/**
	 * “更新”按钮事件方法
	 * @param v
	 */
	public void onUpdateClicked(View v)
	{
		categoryList.clear();
		worker = new Worker();
		worker.start();
		progressDialog = new ProgressDialog(this);
		progressDialog.setCancelable(true);
		progressDialog.setTitle(R.string.joke_category_progress_title);
		progressDialog.setMessage(getText(R.string.joke_category_progress_content));
		progressDialog.setButton(getText(R.string.joke_category_progress_btn_cancel), new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialoginterface, int i)
			{
				worker.kill();
			}
		});
		progressDialog.show();
		synchronized (worker)
		{
			worker.notify();
		}
	}

	/**
	 * “随机”按钮事件方法
	 * @param v
	 */
	public void onRandomClicked(View v)
	{
		Intent random = new Intent();
		random.setClass(this, JokeRandom.class);
		startActivity(random);
	}

	/**
	 * “返回”按钮事件方法
	 * @param v
	 */
	public void onExitClicked(View v)
	{
		finish();
	}

	/**
	 * 网络连接并更新菜单信息的工作者线程
	 * @author shawn
	 *
	 */
	private class Worker extends Thread
	{
		//	线程是否为意外退出的标记
		private boolean cancel = false;

		/**
		 * 强制杀死工作者线程
		 */
		public void kill()
		{
			cancel = true;
			this.interrupt();
		}

		@Override
		public void run()
		{
			try
			{
				//	等待对话框创建完成
				synchronized (this)
				{
					wait();
				}

				//	此处访问网络并获取分类菜单
				fetchCategories(categoryList);

				//	关闭进度对话框并通知界面更新
				progressDialog.dismiss();
				if(! cancel)
				{
					//	在非意外中断情况下才更新界面
					Message msg = new Message();
					msg.what = REFRESHED;
					handler.sendMessage(msg);
				}
				else
				{
					//	意外中断的情况下，显示错误对话框
					Message msg = new Message();
					msg.what = FAILED;
					handler.sendMessage(msg);
				}
			}
			catch (Exception e)
			{
				//	清除按钮列表
				try { progressDialog.dismiss(); } catch (Exception ex) { };
				categoryList.clear();
				//	意外中断的情况下，显示错误对话框
				Message msg = new Message();
				msg.what = FAILED;
				handler.sendMessage(msg);
				Log.d(this.getClass().getName(), "", e);
			}
		}

		//	读取文章分类信息
		private void fetchCategories(List<Pair<String, Integer>> categoryList) throws Exception
		{
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(AddressConstant.JOKE_CATEGORY);
			NodeList list = doc.getElementsByTagName("category");
			int len = list.getLength();
			for(int i = 0; i < len; i ++)
			{
				Pair<String, Integer> pair = new Pair<String, Integer>();
				Node node = list.item(i);
				NodeList nodes = node.getChildNodes();
				int count = nodes.getLength();
				for(int j = 0; j < count; j ++)
				{
					Node pairNode = nodes.item(j);
					String nodeName = pairNode.getNodeName();
					if("id".equals(nodeName))
					{
						String id = pairNode.getTextContent();
						pair.second = Integer.valueOf(id);
					}
					else if("name".equals(nodeName))
					{
						String name = pairNode.getTextContent();
						pair.first = name;
					}
				}
				if(pair.first != null && pair.second != null)
				{
					categoryList.add(pair);
				}
			}
		}
	}
}
